<template>
  <div v-if="visible">
    <el-dialog :visible.sync="visible"
               :title="dataFormTitle"
               :modal="false"
               width="60%"
               class="user-dialog add-or-updata"
               :before-close="closeDialog"
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <el-form :model="dataForm"
               v-loading="dataListLoading"
               :element-loading-text="$t('loading')"
               ref="dataForm"
               label-position="left"
               @keyup.enter.native="dataFormSubmitHandle()"
               label-width="80px">
        <el-form-item prop="taskName"
                      :rules="stringRule()"
                      label="任务名称">
          <el-input v-model="dataForm.taskName"
                    placeholder=""></el-input>
        </el-form-item>
        <el-row type="flex"
                justify="space-between"
                v-if="dataForm.dockingMethod === 1">
          <el-col :span="7">
            <el-form-item prop="platform"
                          :rules="required()"
                          label="平台">
              <el-select v-model="dataForm.platform"
                         clearable
                         class="width-100"
                         placeholder="">
                <el-option v-for="item in platformList"
                           :key="item.id"
                           :label="item.platformName + '-' + getmanufacturersToString(item.manufacturers)"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="7"
                  v-if="dataForm.dockingMethod === 2">
            <el-form-item prop="agreement"
                          :rules="required()"
                          label="协议">
              <el-select v-model="dataForm.agreement"
                         clearable
                         class="width-100"
                         placeholder="请选择">
                <el-option v-for="item in agreementList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="6">
            <el-form-item prop="frequency"
                          class="frequency1"
                          :rules="required()"
                          label="频率">
              <el-input-number v-model="dataForm.frequency"
                               controls-position="right"
                               class="width-100"
                               step-strictly
                               :min="0"
                               :max="99999"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item prop="unit"
                          class="time"
                          label="">
              <el-select v-model="dataForm.unit"
                         clearable
                         class="width-100"
                         placeholder="">
                <el-option v-for="item in timeList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="5">
            <el-form-item prop="unit"
                          class="frequency1"
                          :rules="required()"
                          label="频率">
              <el-select v-model="dataForm.unit"
                         clearable
                         class="width-100"
                         placeholder=""
                         @change="changeTime">
                <el-option v-for="item in timeList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item v-if="dataForm.unit === 1"
                          prop="frequency"
                          class="time"
                          label=""
                          :rules="required()">
              <el-input-number v-model="dataForm.frequency"
                               controls-position="right"
                               class="width-100"
                               step-strictly
                               :min="5"
                               :max="59"></el-input-number>
            </el-form-item>
            <el-form-item v-if="dataForm.unit === 2"
                          prop="frequency"
                          class="time"
                          label=""
                          :rules="required()">
              <el-input-number v-model="dataForm.frequency"
                               controls-position="right"
                               class="width-100"
                               step-strictly
                               :min="0"
                               :max="59"></el-input-number>
            </el-form-item>
            <el-form-item v-if="dataForm.unit === 3"
                          prop="frequency"
                          class="time"
                          label=""
                          :rules="required()">
              <el-time-select v-model="dataForm.frequency"
                              class="width-100"
                              :picker-options="{
                                start: '00:00',
                                step: '00:01',
                                end: '23:59'
                              }"
                              placeholder="选择时间">
              </el-time-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item prop="deviceType"
                          label="设备类型"
                          :rules="required()">
              <el-select v-model="dataForm.deviceType"
                         clearable
                         class="width-100"
                         placeholder="请选择设备类型">
                <el-option v-for="item in EquTypeList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex"
                v-if="dataForm.dockingMethod === 2">
          <el-col :span="6">
            <el-form-item prop="unit"
                          :rules="required()"
                          label="频率">
              <el-select v-model="dataForm.unit"
                         clearable
                         class="width-100"
                         placeholder=""
                         @change="changeTime">
                <el-option v-for="item in timeList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item v-if="dataForm.unit === 1"
                          prop="frequency"
                          class="time"
                          label=""
                          :rules="required()">
              <el-input-number v-model="dataForm.frequency"
                               controls-position="right"
                               class="width-100"
                               step-strictly
                               :min="5"
                               :max="59"></el-input-number>
            </el-form-item>
            <el-form-item v-if="dataForm.unit === 2"
                          prop="frequency"
                          class="time"
                          label=""
                          :rules="required()">
              <el-input-number v-model="dataForm.frequency"
                               controls-position="right"
                               class="width-100"
                               step-strictly
                               :min="0"
                               :max="59"></el-input-number>
            </el-form-item>
            <el-form-item v-if="dataForm.unit === 3"
                          prop="frequency"
                          class="time"
                          label=""
                          :rules="required()">
              <el-time-select v-model="dataForm.frequency"
                              class="width-100"
                              :picker-options="{
                                start: '00:00',
                                step: '00:01',
                                end: '23:59'
                              }"
                              placeholder="选择时间">
              </el-time-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item prop="deviceName"
                      style="text-align: right;">
          <el-button type="primary"
                     plain
                     @click="onAddClick">添加设备</el-button>
        </el-form-item>
        <table-template v-if="dataForm.dockingMethod === 1"
                        :tableData='tableData'
                        :loading='dataListLoading'
                        :dataList='dataList1'
                        class="minh">
          <el-table-column :label="$t('handle')"
                           fixed='right'
                           header-align='center'
                           align='center'
                           width='150'>
            <template slot-scope='scope'>
              <el-button @click="test(scope.row)"
                         type="text"
                         size="mini"
                         :loading="istest"
                         class="band">测试</el-button>
              <el-button @click="deleteRow(scope.$index)"
                         type="text"
                         size="mini"
                         class="danger">删除</el-button>
            </template>
          </el-table-column>
        </table-template>
        <table-template v-if="dataForm.dockingMethod === 2"
                        :tableData='tableData1'
                        :loading='dataListLoading'
                        :dataList='dataList1'
                        class="minh">
          <template slot="name-after">
            <el-table-column prop="deviceType"
                             align="center"
                             label="设备类型"
                             show-overflow-tooltip
                             min-width="80">
              <template slot-scope="scope">
                <span>{{ $store.state.EquTypeList.find(item => item.id === scope.row.deviceType).name }}</span>
              </template>
            </el-table-column>
          </template>
          <el-table-column :label="$t('handle')"
                           fixed='right'
                           header-align='center'
                           align='center'
                           width='150'>
            <template slot-scope='scope'>
              <el-button @click="test(scope.row)"
                         type="text"
                         size="mini"
                         :loading="istest"
                         class="band">测试</el-button>
              <el-button @click="deleteRow(scope.$index)"
                         type="text"
                         size="mini"
                         class="danger">删除</el-button>
            </template>
          </el-table-column>
        </table-template>
      </el-form>
      <template slot="footer">
        <el-button @click="closeDialog()">{{ $t("cancel") }}</el-button>
        <el-button type="primary"
                   :loading="dataListLoading"
                   @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
      </template>
    </el-dialog>
    <el-dialog title=""
               :visible.sync="dialogVisible"
               width="30%"
               :before-close="handleClose">
      <el-form :model="resultObj"
               v-loading="dataListLoading"
               :element-loading-text="$t('loading')"
               ref="resultObj"
               label-position="left"
               label-width="80px">
        <el-form-item v-if="resultObj.status"
                      prop="status"
                      label="结果：">
          <!-- <el-input v-model="resultObj.status"
                    disabled
                    placeholder=""> -->
          <span>{{ resultObj.status === '1' ? '在线' : '离线' }}</span>
          <!-- </el-input> -->
        </el-form-item>
        <div v-else>
          <el-form-item prop="result"
                        label="读数：">
            <el-input v-model="resultObj.result"
                      disabled
                      placeholder=""></el-input>
          </el-form-item>
          <el-form-item prop="dataUnit"
                        label="单位：">
            <el-input v-model="resultObj.dataUnit"
                      disabled
                      placeholder=""></el-input>
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="handleClose()">取 消</el-button>
        <el-button type="primary"
                   @click="dataFormSubmitHandle1()">确 定</el-button>
      </span>
    </el-dialog>
    <equipment-list ref="listDialog"
                    @closeDialog="success" />
    <equipment-list1 ref="listDialog1"
                     @closeDialog="success" />
  </div>
</template>

<script>
import mixinViewModule from '@/mixins/view-module'
import minFormValidate from '@/mixins/form-validate'
import debounce from 'lodash/debounce'
import tableTemplate from '@/components/table-template'
import EquipmentList from './equipment-list.vue'
import EquipmentList1 from './equipment-list1.vue'
export default {
  mixins: [mixinViewModule, minFormValidate],
  data () {
    return {
      mixinViewModuleOptions: {
        updateURL: '/tb/devicePolling/updatePolling', // 添加或修改接口，API地址
        getDataInfoURL: '/tb/devicePolling/queryDetail?id=' // 数据详情，API地址
      },
      dataFormTitle: '修改',
      visible: false,
      EquTypeList: [
        {
          name: '门禁',
          id: 5
        },
        {
          name: '门禁考勤一体机',
          id: 7
        },
        {
          name: '摄像头',
          id: 8
        },
        {
          name: '音频',
          id: 9
        }
      ],
      dataForm: {
        taskName: '',
        platform: '',
        frequency: '',
        unit: 1,
        deviceType: '',
        resultList: []
      },
      platformList: [], // 平台
      manufacturersList: [
        { id: 0, name: '北森' }, // 第三方平台列表
        { id: 1, name: '泛微' },
        { id: 2, name: '企业微信' },
        { id: 3, name: '大华' },
        { id: 4, name: '海康' },
        { id: 5, name: '阿里云' },
        { id: 6, name: 'IPC广播网络平台' }],
      agreementList: [
        { id: 1, name: 'modbus_tcp' },
        { id: 2, name: 'modbus_rtu' },
        { id: 4, name: 'DLT645_2007' }
      ],
      timeList: [
        { id: 1, name: '分钟' },
        { id: 2, name: '小时' },
        { id: 3, name: '天' }
      ],
      arr: [],
      dataList1: [],
      dialogVisible: false,
      resultObj: {},
      istest: false
    }
  },
  components: {
    tableTemplate,
    EquipmentList,
    EquipmentList1
  },
  computed: {
    tableData () {
      return [
        { label: '设备ID', width: '120', prop: 'deviceId' },
        { label: '设备名称', width: '120', prop: 'name' },
        { label: '所在位置', width: '120', prop: 'areaName' },
        { label: '逻辑ID', width: '120', prop: 'logicId' }
      ]
    },
    tableData1 () {
      return [
        { label: '设备ID', width: '120', prop: 'deviceId' },
        { label: '设备名称', width: '120', prop: 'name' },
        { label: '所在位置', width: '120', prop: 'areaName' },
        { label: 'IP', width: '120', prop: 'ip' },
        { label: '采集端口', width: '120', prop: 'gatherPort' },
        { label: '数据标识', width: '120', prop: 'dataIdentification' }
      ]
    }
  },
  methods: {
    init (data) {
      this.dataForm.id = data.id
      this.dataForm = data
      this.visible = true
      this.$nextTick(() => {
        this.getDataInfo().then(res => {
          // if (res.unit === 1 || res.unit === 2) {
          //   this.dataForm.frequency = res.frequency * 1
          // }
          this.arr = []
          this.dataList1 = res.data.resultList
          this.dataList1.map(item => {
            this.arr.push({ id: item.id })
          })
        })
        this.getqQueryList()
      })
    },
    changeTime () {
      this.dataForm.frequency = ''
    },
    // test (data) {
    //   this.istest = true
    //   this.$http.get(`/tb/devicePolling/queryDeviceStauts?id=${data.id}`).then(({ data: res }) => {
    //     if (res.code !== 0) {
    //       this.istest = false
    //       return this.$message.error(res.msg)
    //     }
    //     this.resultObj = res.data
    //     this.istest = false
    //     this.dialogVisible = true
    //   })
    // },
    test (data) {
      this.istest = true
      this.$http.get(`/tb/devicePolling/queryDeviceStauts?id=${data.id}&dockingMethod=${this.dataForm.dockingMethod}`).then(({ data: res }) => {
        if (res.code !== 0) {
          this.istest = false
          return this.$message.error(res.msg)
        }
        this.resultObj = res.data
        this.istest = false
        this.dialogVisible = true
      })
    },
    handleClose () {
      this.istest = false
      this.dialogVisible = false
      this.resultObj = {}
    },
    dataFormSubmitHandle1 () {
      this.handleClose()
    },
    getmanufacturersToString (_id) {
      return this.manufacturersList.find(item => item.id === _id)['name']
    },
    getqQueryList () {
      this.$http.get(`tb/thirdPlatform/queryList?type=2&manufacturers=`).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.platformList = []
        if (res.data.length > 0) {
          this.platformList = res.data
        }
        // manufacturers===10是无效数据
        this.platformList.forEach((item, index) => {
          if (item.manufacturers === 10) {
            this.platformList.splice(index, 1)
          }
        })
      })
    },
    closeDialog () {
      this.visible = false
      this.dataList1 = []
      this.arr = []
      this.dataForm = {
        taskName: '',
        platform: '',
        agreement: '',
        frequency: '',
        unit: 1,
        deviceType: '',
        resultList: []
      }
      this.$emit('callBack')
    },
    success (data) {
      data.map(item => {
        this.dataList1.push(item)
      })
      const removeDuplicateObj = (arr) => {
        // 缓存用于记录
        const newArr = []
        for (const t of arr) {
          // 检查缓存中是否已经存在
          if (
            newArr.find(
              (c) =>
                c.id === t.id &&
                c.age === t.age
            )
          ) {
            // 已经存在说明以前记录过，现在这个就是多余的，直接忽略
            continue
          }
          // 不存在就说明以前没遇到过，把它记录下来
          newArr.push(t)
        }

        // 记录结果就是过滤后的结果
        return newArr
      }
      this.dataList1 = removeDuplicateObj(this.dataList1)
      this.arr = []
      this.dataList1.map(item => {
        this.arr.push({ id: item.id })
      })
    },

    onAddClick () {
      if (this.dataForm.dockingMethod === 1) {
        if (!this.dataForm.deviceType || !this.dataForm.platform) {
          return this.$message.warning('请选择平台和设备类型')
        }
        this.openDialog('listDialog', this.dataList1, this.dataForm)
      } else if (this.dataForm.dockingMethod === 2) {
        // if (!this.dataForm.deviceType || !this.dataForm.agreement) {
        //   return this.$message.warning('请选择协议和设备类型')
        // }
        this.openDialog('listDialog1', this.dataList1, this.dataForm)
      }
    },
    // table删除行
    deleteRow (index) {
      this.dataList1.splice(index, 1)
      this.arr = []
      this.dataList1.map(item => {
        this.arr.push({ id: item.id })
      })
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs.dataForm.validate((valid) => {
          if (valid) {
            this.dataForm.resultList = this.arr
            let a = this.dataForm.frequency.toString()
            delete this.dataForm.frequency
            this.dataForm.frequency = a
            const url = this.mixinViewModuleOptions.updateURL
            // this.addOrUpdateItem({ url }).then((res) => {
            //   if (res.code !== 0) {
            //     return
            //   }
            //   this.closeDialog()
            // })
            this.$http.put(url, this.dataForm).then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg)
              }
              this.closeDialog()
            })
          }
        })
      },
      1000,
      { leading: true, trailing: false }
    )
  }
}
</script>

<style lang="scss" scoped>
.minh {
  max-height: 420px !important;
  overflow: auto;
}
.frequency1 {
  ::deep.el-form-item__label {
    width: 60px !important;
  }

  ::deep.el-form-item__content {
    margin-left: 60px !important;
  }
}

.time {
  ::deep.el-form-item__label {
    width: 10px !important;
  }

  ::deep.el-form-item__content {
    margin-left: 10px !important;
  }
}
</style>
